<template>
    <div class="old-user-list" id="old-user-list">
        <Layout>
            <Header class="header">
                <Row>
                    <Col :span="24">
                    <div>
                        <span class="border-left"></span>
                        1.0用户列表
                    </div>
                    </Col>
                </Row>
            </Header>
            <Content class="content">
                <div class="search-box">
                    <Row :gutter="16" style="min-width: 1024px">
                        <Col :span="6">
                            用户账号：
                            <Input v-model="searchForm.account" placeholder="用户ID/账号" style="width:auto" />
                        </Col>
                        <Col :span="6">
                            <div class="search-btn" @click="getTableData(1)">查询</div>
                        </Col>
                    </Row>
                </div>

                <div class="table-box">
                    <el-table ref="table" :data="tableData" size="mini" style="width: 100%;min-width: 800px">
                        <el-table-column align="center" prop="id" label="ID"></el-table-column>
                        <el-table-column align="center" label="微信昵称">
                            <template slot-scope="scope">
                                <p>{{scope.row.wechat_linkname ? scope.row.wechat_linkname : '（暂无）'}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="account" label="用户账号"></el-table-column>
                        <el-table-column align="center" label="用户昵称">
                            <template slot-scope="scope">
                                <p>{{scope.row.name ? scope.row.name : '（暂无）'}}</p>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column
                            align="center"
                            label="身份证号码">
                            <template slot-scope="scope">
                                <p>{{scope.row.real.idcard || '（暂无）'}}</p>
                            </template>
                        </el-table-column> -->
                        <el-table-column
                            align="center"
                            prop="rec_code"
                            label="推荐码">
                        </el-table-column>
                        <el-table-column align="center" prop="parent_id" label="上级ID"></el-table-column>
                        <el-table-column align="center" label="收益余额">
                            <template slot-scope="scope">
                                <p>￥{{scope.row.balance}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="工资总额">
                            <template slot-scope="scope">
                                <p>￥{{scope.row.wages_sum || '0.00'}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="工资余额">
                            <template slot-scope="scope">
                                <p>￥{{scope.row.wages || '0.00'}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="短期收益">
                            <template slot-scope="scope">
                                <p>￥{{scope.row.my_profit || '0.00'}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="短期收益已提现">
                            <template slot-scope="scope">
                                <p>￥{{scope.row.profit_used_cash || '0.00'}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="注册时间">
                            <template slot-scope="scope">
                                <p>{{scope.row.create_time.split(' ')[0]}}</p>
                            </template>
                        </el-table-column>
                        
                        <el-table-column label="操作" width="200" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="look(scope.row)">查看详情</el-button>
                                <!-- <el-button type="text" size="small" @click="roleConfig(scope.row.id,scope.row.rate)">角色设定</el-button> -->
                                <el-button type="text" size="small" @click="editInfo(scope.row.id,scope.row.rate,scope.row)">信息编辑</el-button>
                                <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <el-dialog width="70%" title="用户信息修改" :visible.sync="dialogFormVisible1" class="dialog_box" :before-close="handleCancel" :close-on-click-modal="false">
                    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="160" style="width:100%">
                        <FormItem label="用户账号" prop="account">
                            <Input style="width: 50%" v-model="formValidate.account"></Input>
                        </FormItem>
                        <FormItem label="大众钱包" prop="balance">
                            <Input style="width: 50%" v-model="formValidate.balance"></Input>
                        </FormItem>
                        <FormItem label="工资" prop="wages">
                            <Input style="width: 50%" v-model="formValidate.wages"></Input>
                        </FormItem>
                        <FormItem label="短期收益" prop="my_profit">
                            <Input style="width: 50%" v-model="formValidate.my_profit"></Input>
                        </FormItem>
                        <FormItem label="绑定关系" prop="parent_id">
                            <Input v-model="formValidate.parent_id" disabled style="width: 10%;box-sizing: border-box"></Input>
                            <Input v-model="searchAccount" placeholder="请输入上级账号进行检索，如无上级关系请勿进行操作" style="width: 40%;box-sizing: border-box">
                                <Icon type="ios-search" slot="suffix" @click="search" />
                            </Input>
                        </FormItem>

                        <FormItem label="角色设置">
                            <el-checkbox-group size="mini" disabled v-model="selectedRoles" @change="roleChange1">
                                <el-checkbox border label="省级代理" v-show="isProviceShow">省级代理</el-checkbox>
                                <el-checkbox border label="市级代理" v-show="isTownShow">市级代理</el-checkbox>
                                <el-checkbox border label="县级代理" v-show="isAreaShow">县级代理</el-checkbox>
                                <el-checkbox border label="合伙人" v-show="isRateShow">合伙人</el-checkbox>
                                <el-checkbox border label="个人代理" v-show="isSelfShow">个人代理</el-checkbox>
                                <el-checkbox border label="推广员" v-show="isPromoteShow">推广员</el-checkbox>
                            </el-checkbox-group>
                        </FormItem>

                        <Divider v-show="isAreaShow || isTownShow || isProviceShow" />

                        <div class="lable_title_box" v-show="isAreaShow || isTownShow || isProviceShow" style="display: flex;margin-bottom: 10px">
                            <div style="width:160px"></div>
                            <div style="width:200px;margin-right:4px">代理区域</div>
                            <div style="width: 100px;margin-right: 10px">代理提成</div>
                            <div style="width: 100px;margin-right: 10px">代理收益</div>
                            <div style="width: 100px;margin-right: 10px">推荐人收益</div>
                            <div style="width: 100px;margin-right: 10px">订单总额</div>
                        </div>

                        <div class="ivu-form-item hidden fead" :class="isProviceShow ? 'show' : ''">
                            <label class="ivu-form-item-label" style="width: 160px;">代理区域(省级)</label>
                            <div class="ivu-form-item-content  u_content" style="margin-left: 120px;">
                                <div class="u_input_box" v-for="(item,i) in formData.province" :key="i">
                                    <Cascader class="u_input" :data="province" filterable v-model="item.address"></Cascader>
                                    <Input style="width:100px;margin-right: 10px" placeholder="省级提成" v-model="item.rate">
                                        <span slot="append">%</span>
                                    </Input>
                                    <Input style="width:100px;margin-right: 10px" placeholder="省级收益" v-model="item.balance">
                                    </Input>
                                    <Input style="width:100px;margin-right: 10px" placeholder="推荐人收益" v-model="item.rec_balance">
                                    </Input>
                                    <Input style="width:100px;margin-right: 10px" placeholder="订单总额" v-model="item.region_order_total">
                                    </Input>
                                    <!-- <DatePicker @on-change="dateSet($event,item)" disabled :options="options" :start-date="new Date(new Date() - (30*24*60*60*1000))"
                                        type="date" placement="bottom" format="yyyy-MM-dd" placeholder="成为代理时间" style="width: auto">
                                    </DatePicker> -->
                                    <!-- <div class="addArea addBtn" v-show="i != formData.province.length-1" @click="minuProvince(i)">-</div> -->
                                </div>
                                <!-- <div class="addArea addBtn" @click="addProvince">+</div> -->
                            </div>
                        </div>

                        <div class="ivu-form-item hidden fead" :class="isTownShow ? 'show' : ''">
                            <label class="ivu-form-item-label" style="width: 160px;">代理区域(市级)</label>
                            <div class="ivu-form-item-content  u_content" style="margin-left: 120px;">
                                <div class="u_input_box" v-for="(item,i) in formData.town" :key="i">
                                    <Cascader class="u_input" :data="town" :load-data="loadTownData" filterable v-model="formData.town[i].address"></Cascader>
                                    <Input style="width:100px;margin-right: 10px" placeholder="市级提成" v-model="item.rate">
                                        <span slot="append">%</span>
                                    </Input>
                                    <Input style="width:100px;margin-right: 10px" placeholder="市级收益" v-model="item.balance">
                                    </Input>
                                    <Input style="width:100px;margin-right: 10px" placeholder="推荐人收益" v-model="item.rec_balance">
                                    </Input>
                                    <Input style="width:100px;margin-right: 10px" placeholder="订单总额" v-model="item.region_order_total">
                                    </Input>
                                    <!-- <DatePicker @on-change="dateSet($event,item)" :options="options" :start-date="new Date(new Date() - (30*24*60*60*1000))"
                                        type="date" placement="bottom" format="yyyy-MM-dd" placeholder="成为代理时间" style="width: auto">
                                    </DatePicker> -->
                                    <!-- <div class="addArea addBtn" v-show="i != formData.town.length-1" @click="minuTown(i)">-</div> -->
                                </div>
                                <!-- <div class="addArea addBtn" @click="addTown">+</div> -->
                            </div>
                        </div>

                        <div class="ivu-form-item hidden fead" :class="isAreaShow ? 'show' : ''">
                            <label class="ivu-form-item-label" style="width: 160px;">代理区域(县级)</label>
                            <div class="ivu-form-item-content u_content" style="margin-left: 120px;">
                                <div class="u_input_box" v-for="(item,i) in formData.area" :key="i">
                                    <Cascader class="u_input" :data="area" :load-data="loadAreaData" filterable v-model="formData.area[i].address"></Cascader>
                                    <Input style="width:100px;margin-right: 10px" placeholder="县级提成" v-model="item.rate">
                                        <span slot="append">%</span>
                                    </Input>
                                    <Input style="width:100px;margin-right: 10px" placeholder="县级收益" v-model="item.balance">
                                    </Input>
                                    <Input style="width:100px;margin-right: 10px" placeholder="推荐人收益" v-model="item.rec_balance">
                                    </Input>
                                    <Input style="width:100px;margin-right: 10px" placeholder="订单总额" v-model="item.region_order_total">
                                    </Input>
                                    <!-- <DatePicker @on-change="dateSet($event,item)" :options="options" :start-date="new Date(new Date() - (30*24*60*60*1000))"
                                        type="date" placement="bottom" format="yyyy-MM-dd" placeholder="成为代理时间" style="width: auto">
                                    </DatePicker> -->
                                    <!-- <div class="addArea addBtn" v-show="i != formData.area.length-1" @click="minuArea(i)">-</div> -->
                                </div>
                                <!-- <div class="addArea addBtn" @click="addArea">+</div> -->
                            </div>
                        </div>

                        <Divider v-show="isRateShow || isSelfShow || isPromoteShow" />

                        <div class="lable_title_box" v-show="isRateShow || isSelfShow || isPromoteShow" style="display: flex;margin-bottom: 10px">
                            <div style="width:160px"></div>
                            <!-- <div style="width:200px;margin-right:4px">代理区域</div> -->
                            <div style="width: 100px;margin-right: 10px">代理提成</div>
                            <div style="width: 100px;margin-right: 10px">代理收益</div>
                            <div style="width: 100px;margin-right: 10px">推荐人收益</div>
                            <div style="width: 100px;margin-right: 10px">订单总额</div>
                        </div>

                        <div class="ivu-form-item fead hidden" :class="isRateShow ? 'show' : ''">
                            <label class="ivu-form-item-label" style="width: 160px;">合伙人</label>
                            <div class="ivu-form-item-content u_content" style="margin-left: 120px;">
                                <Input v-model="formData.partner.rate" style="width:100px;margin-right: 10px" placeholder="合伙人提成">
                                    <span slot="append">%</span>
                                </Input>
                                <Input style="width:100px;margin-right: 10px" placeholder="合伙人收益" v-model="formData.partner.balance">
                                </Input>
                                <Input style="width:100px;margin-right: 10px" placeholder="推荐人收益" v-model="formData.partner.rec_balance">
                                </Input>
                                <Input style="width:100px;margin-right: 10px" placeholder="订单总额" v-model="formData.partner.region_order_total">
                                </Input>
                                <!-- <DatePicker @on-change="dateSet($event,formData.partner)" :options="options" :start-date="new Date(new Date() - (30*24*60*60*1000))"
                                    type="date" placement="bottom" format="yyyy-MM-dd" placeholder="成为合伙人时间" style="width: auto">
                                </DatePicker> -->
                            </div>
                        </div>

                        <div class="ivu-form-item fead hidden" :class="isSelfShow ? 'show' : ''">
                            <label class="ivu-form-item-label" style="width: 160px;">个人代理</label>
                            <div class="ivu-form-item-content u_content" style="margin-left: 120px;">
                                <Input v-model="formData.self.rate" style="width:100px;margin-right: 10px" placeholder="个人代理提成">
                                    <span slot="append">%</span>
                                </Input>
                                <Input style="width:100px;margin-right: 10px" placeholder="个人代理收益" v-model="formData.self.balance">
                                </Input>
                                <Input style="width:100px;margin-right: 10px" placeholder="推荐人收益" v-model="formData.self.rec_balance">
                                </Input>
                                <Input style="width:100px;margin-right: 10px" placeholder="订单总额" v-model="formData.self.region_order_total">
                                </Input>
                                <!-- <DatePicker @on-change="dateSet($event,formData.self)" :options="options" :start-date="new Date(new Date() - (30*24*60*60*1000))"
                                    type="date" placement="bottom" format="yyyy-MM-dd" placeholder="成为代理时间" style="width: auto">
                                </DatePicker> -->
                            </div>
                        </div>

                        <div class="ivu-form-item fead hidden" :class="isPromoteShow ? 'show' : ''">
                            <label class="ivu-form-item-label" style="width: 160px;">推广员</label>
                            <div class="ivu-form-item-content u_content" style="margin-left: 120px;">
                                <Input v-model="formData.promote.rate" style="width:100px;margin-right: 10px" placeholder="推广员提成">
                                    <span slot="append">%</span>
                                </Input>
                                <Input style="width:100px;margin-right: 10px" placeholder="推广员收益" v-model="formData.promote.balance">
                                </Input>
                                <Input style="width:100px;margin-right: 10px" placeholder="推荐人收益" v-model="formData.promote.rec_balance">
                                </Input>
                                <Input style="width:100px;margin-right: 10px" placeholder="订单总额" v-model="formData.promote.region_order_total">
                                </Input>
                                <!-- <DatePicker @on-change="dateSet($event,formData.promote)" :options="options" :start-date="new Date(new Date() - (30*24*60*60*1000))"
                                    type="date" placement="bottom" format="yyyy-MM-dd" placeholder="成为推广员时间" style="width: auto">
                                </DatePicker> -->
                            </div>
                        </div>

                        <FormItem class="right">
                            <!-- <Button type="primary" @click="handleSubmit('formValidate')">提交</Button> -->
                            <Button type="primary" @click="submit">提交</Button>
                            <!-- <Button @click="() => {$refs.formValidate.resetFields()}" style="margin-left: 8px">重置</Button> -->
                        </FormItem>
                    </Form>
                </el-dialog>

                <div class="page-box">
                    <Page :total="total" :page-size="pageSize" show-elevator show-total @on-change="pageChange" />
                </div>
            </Content>

            <Modal
                title="检索结果"
                v-model="searchModel"
                :mask-closable="false"
                @on-ok="addID">
                <p>账号：{{searchAccount}}</p>
                <p>姓名：{{searchName}}</p>
                <p>ID: {{searchID}}</p>
            </Modal>

            <Footer>
                <p class="copy-right">Copyright © {{host}}, All Rights Reserved.</p>
            </Footer>
        </Layout>
    </div>
</template>

<script>
    import * as api from '@/api/api'
    export default {
        data() {
            return {
                host: window.location.host,
                loading: this.$store.state,
                searchForm: {
                    account: '',
                    name: ''
                },
                create_time_search: '',
                create_time: ['', ''],
                options: {
                    disabledDate(date) {
                        return date && date.valueOf() > Date.now();
                    }
                }, //日期选择范围配置
                tableData: [], //表格数据
                dialogFormVisible1: false,
                roles: [],
                selectedRoles: [],
                province: [], //省
                town: [], //市
                area: [], //区县
                formData: {
                    area: [],
                    town: [],
                    province: [],
                    partner: {
                        rate: '',
                        city_id: '10002',
                        territory: '中国',
                        role_id: '2',
                        balance: '',
                        rec_balance: '',
                        region_order_total: '',
                        agent_time: ''
                    },
                    self: {
                        rate: '',
                        city_id: '10006',
                        territory: '中国',
                        role_id: '6',
                        balance: '',
                        rec_balance: '',
                        region_order_total: '',
                        agent_time: ''
                    },
                    promote: {
                        rate: '',
                        city_id: '10009',
                        territory: '中国',
                        role_id: '9',
                        balance: '',
                        rec_balance: '',
                        region_order_total: '',
                        agent_time: ''
                    }
                },
                editUserId: null,
                isAreaShow: false,
                isTownShow: false,
                isProviceShow: false,
                isRateShow: false,
                isSelfShow: false,
                isPromoteShow: false,
                total: 0, //数据总条数
                pageSize: 10, //每页显示条数
                current_page: 1, //当前页码
                // ------------------------------------------------------------
                formValidate: {
                    account: '',
                    balance: '',
                    wages: '',
                    my_profit: '',
                    parent_id: '0'
                },
                ruleValidate: {
                    account: [
                        { required: true, message: '请填写用户账号', trigger: 'blur' }
                    ],
                    balance: [
                        { required: true, message: '请填写用户大众钱包余额', trigger: 'blur' }
                    ],
                    wages: [
                        { required: true, message: '请填写用户工资余额', trigger: 'blur' }
                    ],
                    my_profit: [
                        { required: true, message: '请填写用户短期收益', trigger: 'blur' }
                    ]
                },
                searchAccount: '',
                searchName: '',
                searchID: '',
                searchModel: false,
                body1: null,
                body2: null,
            }
        },
        mounted() {
            this.getTableData(0);
        },

        computed: {

        },

        watch: {

        },

        methods: {
            pageChange(current_page) {
                this.current_page = current_page;
                this.getTableData(3);
            },

            getTableData(index) {
                if (index === 1 || index === 0) {
                    this.current_page = 1;
                };
                let body = {
                    offset: this.current_page - 1,
                    limit: this.pageSize
                }
                // if (this.create_time_search) {
                //     body.condition.create_time = this.create_time_search
                // }
                if(this.searchForm.account) {
                    body.search_account = this.searchForm.account;
                }
                this.loading.isLoading = true;
                api.oldUserList(body).then(res => {
                    this.loading.isLoading = false;
                    if (res.data.code === 200) {
                        let data = res.data.data
                        this.total = data.count * 1;
                        this.tableData = data.data;
                        this.getProvince()
                    } else {
                        this.$Notice.error({
                            title: '错误',
                            desc: res.data.msg
                        });
                    }
                }).catch(err => {
                    this.loading.isLoading = false;
                    this.$Notice.error({
                        title: '错误',
                        desc: '服务器错误,请联系管理员（' + err + '）',
                    });
                });
            },

            submit() {
                this.$refs.formValidate.validate((valid) => {
                    if (valid) {
                        if(!this.bodySet()) {
                            return false;
                        };
                        this.loading.isLoading = true;
                        let body = this.formValidate;
                        body.uid = this.editUserId;
                        api.editOldUserInfo(body).then(res => {
                            if(res.data.code === 200) {
                                let bodys = [];
                                let addBody = (datas) => {
                                    for (const item of datas) {
                                        bodys.push(item)
                                    }
                                }
                                let formData = this.formData;
                                let roles = this.selectedRoles.join(',');
                                let re1 = new RegExp('省级代理');
                                let re2 = new RegExp('市级代理');
                                let re3 = new RegExp('县级代理');
                                let re4 = new RegExp('合伙人');
                                let re5 = new RegExp('个人代理');
                                let re6 = new RegExp('推广员');
                                if(re1.test(roles)) {
                                    addBody(formData.province);
                                }
                                if(re2.test(roles)) {
                                    addBody(formData.town);
                                }
                                if(re3.test(roles)) {
                                    addBody(formData.area);
                                }
                                if(re4.test(roles)) {
                                    bodys.push(formData.partner)
                                }
                                if(re5.test(roles)) {
                                    bodys.push(formData.self)
                                }
                                if(re6.test(roles)) {
                                    bodys.push(formData.promote)
                                }
                                let submitAgentFn = this.submitAgent(bodys);
                                submitAgentFn(0)
                            }
                        }).catch(err => {
                            console.log(err)
                        })
                    }
                })
                
            },

            submitAgent(bodys) {
                let i = 0
                let len = bodys.length
                var _vm = this;
                return function recursion (data) {
                    if (i >= len) {
                        if(data.code === 200) {
                            _vm.loading.isLoading = false;
                            _vm.$Notice.success({
                                title: '提示',
                                desc: '修改成功！'
                            })
                            _vm.handleCancel()
                            _vm.getTableData()
                        }else {
                            _vm.$Notice.error({
                                title: '错误',
                                desc: '修改失败！'
                            })
                             _vm.loading.isLoading = false;
                        }
                        return false
                    } // 最后一次请求的结果
                    let body = bodys[i++]
                    api.editAgentInfo(body).then(res => {
                        if(res.data.code === 200) {
                            recursion(res.data)
                        }else {
                            _vm.$Notice.error({
                                title: '错误',
                                desc: '修改失败！'
                            })
                             _vm.loading.isLoading = false;
                            return false;
                        }
                    })
                }
            },

            bodySet() {
                var body = {...this.formValidate};
                if(this.selectedRoles.length > 0) {
                    var role_info = [];
                    let roles = this.selectedRoles.join(',');
                    let re1 = new RegExp('省级代理');
                    let re2 = new RegExp('市级代理');
                    let re3 = new RegExp('县级代理');
                    let re4 = new RegExp('合伙人');
                    let re5 = new RegExp('个人代理');
                    let re6 = new RegExp('推广员');
                    if(re1.test(roles)) {
                        for (const item of this.formData.province) {
                            let one = {...item};
                            try {
                                one.city_id = item.address[0].split(',')[1];
                                one.territory = item.address[0].split(',')[0];
                                role_info.push(one)
                            } catch(err) {
                                this.$Notice.error({
                                    title: '错误',
                                    desc: '请选择代理区域',
                                });
                                return false;
                            }
                            one.rate = one.rate || '0';
                            one.balance = one.balance || '0';
                            one.rec_balance = one.rec_balance || '0';
                            one.region_order_total = one.region_order_total || '0';
                            one.agent_time = one.agent_time || '2018-12-12 00:00:00';
                            role_info.push(one)
                        }
                    }
                    if(re2.test(roles)) {
                        for (const item of this.formData.town) {
                            let one = {...item};
                            try {
                                one.city_id = item.address[1].split(',')[1];
                                one.territory = item.address[0] + '/' + item.address[1].split(',')[0];
                            } catch(err) {
                                this.$Notice.error({
                                    title: '错误',
                                    desc: '请选择代理区域',
                                });
                                return false;
                            }
                            one.rate = one.rate || '0';
                            one.balance = one.balance || '0';
                            one.rec_balance = one.rec_balance || '0';
                            one.region_order_total = one.region_order_total || '0';
                            one.agent_time = one.agent_time || '2018-12-12 00:00:00';
                            role_info.push(one)
                        }
                    }
                    if(re3.test(roles)) {
                        for (const item of this.formData.area) {
                            let one = {...item};
                            try {
                                one.city_id = item.address[2].split(',')[1];
                                one.territory = item.address[0] + '/' + item.address[1] + '/' + item.address[2].split(',')[0];
                            } catch(err) {
                                this.$Notice.error({
                                    title: '错误',
                                    desc: '请选择代理区域',
                                });
                                return false;
                            }
                            one.rate = one.rate || '0';
                            one.balance = one.balance || '0';
                            one.rec_balance = one.rec_balance || '0';
                            one.region_order_total = one.region_order_total || '0';
                            one.agent_time = one.agent_time || '2018-12-12 00:00:00';
                            role_info.push(one)
                        }
                    }
                    if(re4.test(roles)) {
                        let one = {...(this.formData.partner)};
                        // let one = this.formData.partner;
                        one.rate = one.rate || '0';
                        one.balance = one.balance || '0';
                        one.rec_balance = one.rec_balance || '0';
                        one.region_order_total = one.region_order_total || '0';
                        one.agent_time = one.agent_time || '2018-12-12 00:00:00';
                        role_info.push(one);
                    }
                    if(re5.test(roles)) {
                        let one = {...(this.formData.self)};
                        // let one = this.formData.self;
                        one.rate = one.rate || '0';
                        one.balance = one.balance || '0';
                        one.rec_balance = one.rec_balance || '0';
                        one.region_order_total = one.region_order_total || '0';
                        one.agent_time = one.agent_time || '2018-12-12 00:00:00';
                        role_info.push(one)
                    }
                    if(re6.test(roles)) {
                        let one = {...(this.formData.promote)};
                        // let one = this.formData.promote;
                        one.rate = one.rate || '0';
                        one.balance = one.balance || '0';
                        one.rec_balance = one.rec_balance || '0';
                        one.region_order_total = one.region_order_total || '0';
                        one.agent_time = one.agent_time || '2018-12-12 00:00:00';
                        role_info.push(one)
                    }
                    if(role_info.length > 0) {
                        body.role_info = JSON.stringify(role_info)
                    }
                }
                this.body = body;
                return true;
            },

            look(row) {
                this.$router.push({
                    name: 'UserDetails',
                    params: {
                        userId: row.id,
                        balance: row.balance
                    }
                })
            },

            search() {
                if(!this.searchAccount) {
                    this.$Notice.error({
                        title: '错误',
                        desc: "请先填写上级账号",
                    });
                    this.formValidate.parent_id = '0';
                    return false
                }
                let body = {
                    account: this.searchAccount
                };
                api.searchAccount(body).then(res => {
                    if(res.data.code === 200) {
                        this.searchModel = true;
                        this.searchID = res.data.data.parent_id;
                        this.searchName = res.data.data.name;
                    }else {
                        this.$Notice.error({
                            title: '错误',
                            desc: res.data.msg,
                        });
                        this.formValidate.parent_id = '0';
                    }
                }).catch(err => {
                    this.$Notice.error({
                        title: '错误',
                        desc: '服务器开小差了，请稍后再试！',
                    });
                })
            },

            addID() {
                this.formValidate.parent_id = this.searchID;
            },

            
            //信息修改
            editInfo(userId,rate,item) {
                this.editUserId = userId;
                this.isAreaShow = false;
                this.isTownShow = false;
                this.isProviceShow = false;
                this.isRateShow = false;
                this.isSelfShow = false,
                this.isPromoteShow = false,
                this.selectedRoles = [];
                this.formValidate.account = item.account;
                this.formValidate.balance = item.balance;
                this.formValidate.wages = item.wages;
                this.formValidate.my_profit = item.my_profit;
                this.formValidate.parent_id = item.parent_id;
                this.formData = {
                    area: [],
                    town: [],
                    province: [],
                    partner: {
                        rate: '',
                        city_id: '10002',
                        territory: '中国',
                        role_id: '2',
                        balance: '',
                        rec_balance: '',
                        region_order_total: '',
                        agent_time: ''
                    },
                    self: {
                        rate: '',
                        city_id: '10006',
                        territory: '中国',
                        role_id: '6',
                        balance: '',
                        rec_balance: '',
                        region_order_total: '',
                        agent_time: ''
                    },
                    promote: {
                        rate: '',
                        city_id: '10009',
                        territory: '中国',
                        role_id: '9',
                        balance: '',
                        rec_balance: '',
                        region_order_total: '',
                        agent_time: ''
                    }
                };
                let body = {
                    uid: userId
                }
                this.loading.isLoading = true;
                api.getRoleInfo(body).then(res => {
                    this.loading.isLoading = false;
                    if(res.data.code == 200) {
                        for (const item of res.data.data.data) {
                            if(item.role_id == 3) {
                                this.selectedRoles.push('省级代理');
                                let one = {
                                    address: [],
                                    rate: '',
                                    balance: '',
                                    rec_balance: '',
                                    region_order_total: '',
                                    agent_time: '',
                                    id: item.id
                                }
                                one.address.push(item.territory + ',' + item.city_id);
                                one.rate = item.rate;
                                one.territory = item.territory;
                                one.balance = item.balance;
                                one.rec_balance = item.rec_balance;
                                one.region_order_total = item.region_order_total;
                                one.agent_time = item.create_time;
                                this.formData.province.push(one);
                            }
                            if(item.role_id == 4) {
                                this.selectedRoles.push('市级代理');
                                let one = {
                                    address: [],
                                    rate: '',
                                    balance: '',
                                    rec_balance: '',
                                    region_order_total: '',
                                    agent_time: '',
                                    id: item.id
                                }
                                one.address.push(item.territory.split('/')[0],item.territory.split('/')[1] + ',' + item.city_id);
                                one.rate = item.rate;
                                one.territory = item.territory;
                                one.balance = item.balance;
                                one.rec_balance = item.rec_balance;
                                one.region_order_total = item.region_order_total;
                                one.agent_time = item.create_time;
                                this.formData.town.push(one);
                            }
                            if(item.role_id == 5) {
                                this.selectedRoles.push('县级代理')
                                let one = {
                                    address: [],
                                    rate: '',
                                    balance: '',
                                    rec_balance: '',
                                    region_order_total: '',
                                    agent_time: '',
                                    id: item.id
                                }
                                one.address.push(item.territory.split('/')[0],item.territory.split('/')[1],item.territory.split('/')[2] + ',' + item.city_id);
                                one.rate = item.rate;
                                one.territory = item.territory;
                                one.balance = item.balance;
                                one.rec_balance = item.rec_balance;
                                one.region_order_total = item.region_order_total;
                                one.agent_time = item.create_time;
                                this.formData.area.push(one);
                            }
                            if(item.role_id == 2) {
                                this.selectedRoles.push('合伙人');
                                let one = {
                                    rate: '',
                                    city_id: '10002',
                                    territory: '中国',
                                    role_id: '2',
                                    balance: '',
                                    rec_balance: '',
                                    region_order_total: '',
                                    agent_time: '',
                                    id: item.id
                                }
                                one.rate = item.rate;
                                one.balance = item.balance;
                                one.rec_balance = item.rec_balance;
                                one.region_order_total = item.region_order_total;
                                one.agent_time = item.create_time;
                                this.formData.partner = one;
                            }
                            if(item.role_id == 6) {
                                this.selectedRoles.push('个人代理')
                                let one = {
                                    rate: '',
                                    city_id: '10006',
                                    territory: '中国',
                                    role_id: '6',
                                    balance: '',
                                    rec_balance: '',
                                    region_order_total: '',
                                    agent_time: '',
                                    id: item.id
                                }
                                one.rate = item.rate;
                                one.balance = item.balance;
                                one.rec_balance = item.rec_balance;
                                one.region_order_total = item.region_order_total;
                                one.agent_time = item.create_time;
                                this.formData.self = one;
                            }
                            if(item.role_id == 9) {
                                this.selectedRoles.push('推广员')
                                let one = {
                                    rate: '',
                                    city_id: '10009',
                                    territory: '中国',
                                    role_id: '9',
                                    balance: '',
                                    rec_balance: '',
                                    region_order_total: '',
                                    agent_time: '',
                                    id: item.id
                                }
                                one.rate = item.rate;
                                one.balance = item.balance;
                                one.rec_balance = item.rec_balance;
                                one.region_order_total = item.region_order_total;
                                one.agent_time = item.create_time;
                                this.formData.promote = one;
                            }
                            this.selectedRoles = this.uniq(this.selectedRoles);
                            this.roleChange1()
                        }
                    }else {
                        this.$Notice.error({
                            title: '错误',
                            desc: res.data.msg
                        });
                    }

                }).catch(err => {
                    console.error(err)
                })
                this.dialogFormVisible1 = true;
            },

            //数组去重
            uniq(array) {
                let temp = [];
                let index = [];
                let l = array.length;
                for(let i = 0; i < l; i++) {
                    for(let j = i + 1; j < l; j++){
                        if (array[i] === array[j]){
                            i++;
                            j = i;
                        }
                    }
                    temp.push(array[i]);
                    index.push(i);
                }
                return temp;
            },

            roleChange1() {
                let roles = this.selectedRoles.join(',');
                let re1 = new RegExp('省级代理');
                let re2 = new RegExp('市级代理');
                let re3 = new RegExp('县级代理');
                let re4 = new RegExp('合伙人');
                let re5 = new RegExp('个人代理');
                let re6 = new RegExp('推广员');
                if(re1.test(roles)) {
                    this.isProviceShow = true;
                }else {
                    this.isProviceShow = false;
                    this.formData.province = [];
                }
                if(re2.test(roles)) {
                    this.isTownShow = true;
                }else {
                    this.isTownShow = false;
                    this.formData.town = []
                }
                if(re3.test(roles)) {
                    this.isAreaShow = true
                }else {
                    this.isAreaShow = false;
                    this.formData.area = []
                }
                if(re4.test(roles)) {
                    this.isRateShow = true
                }else {
                    this.isRateShow  = false;
                    this.formData.partner = {
                        rate: '',
                        city_id: '10002',
                        territory: '中国',
                        role_id: '2',
                        balance: '',
                        rec_balance: '',
                        region_order_total: '',
                        agent_time: ''
                    }
                }
                if(re5.test(roles)) {
                    this.isSelfShow = true
                }else {
                    this.isSelfShow = false;
                    this.formData.self = {
                        rate: '',
                        city_id: '10006',
                        territory: '中国',
                        role_id: '6',
                        balance: '',
                        rec_balance: '',
                        region_order_total: '',
                        agent_time: ''
                    }
                }
                if(re6.test(roles)) {
                    this.isPromoteShow = true
                }else {
                    this.isPromoteShow = false
                    this.formData.promote = {
                        rate: '',
                        city_id: '10009',
                        territory: '中国',
                        role_id: '9',
                        balance: '',
                        rec_balance: '',
                        region_order_total: '',
                        agent_time: ''
                    }
                }
            },

            dateSet(e,item) {
                let date = e || '2018-12-12'
                item.agent_time = date + ' ' + '00:00:00';
            },

            handleSubmit() {
                
            },

            handleCancel() {
                this.dialogFormVisible1 = false;
            },

            addProvince() {
                let one = {
                    address: [],
                    rate: '',
                    role_id: '3',
                    balance: '',
                    rec_balance: '',
                    region_order_total: '',
                    agent_time: ''
                }
                this.formData.province.push(one)
            },

            minuProvince(i) {
                this.formData.province.splice(i,1);
            },

            addTown() {
                let one = {
                    address: [],
                    rate: '',
                    role_id: '4',
                    balance: '',
                    rec_balance: '',
                    region_order_total: '',
                    agent_time: ''
                }
                this.formData.town.push(one)
            },

            minuTown(i) {
                this.formData.town.splice(i,1);
            },

            addArea() {
                let one = {
                    address: [],
                    rate: '',
                    role_id: '5',
                    balance: '',
                    rec_balance: '',
                    region_order_total: '',
                    agent_time: ''
                }
                this.formData.area.push(one)
            },

            minuArea(i) {
                this.formData.area.splice(i,1);
            },

            del(id) {
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let body = {
                        model: "Users",
                        data: {
                            is_delete: 1
                        },
                        update_condition: {
                            id: id
                        }
                    };
                    this.loading.isLoading = true;
                    api.createData(body).then(res => {
                        if (res.data.code === 200) {
                            this.getTableData();
                            this.$Message.success('删除成功');
                        } else {
                            this.loading.isLoading = false;
                            this.$Notice.error({
                                title: '错误',
                                desc: res.data.msg
                            });
                        }
                    }).catch(err => {
                        this.loading.isLoading = false;
                        this.$Notice.error({
                            title: '错误',
                            desc: '服务器错误,请联系管理员（' + err + '）',
                        });
                    });
                })
            },
            //省市区
            getProvince() {
                let body = {
                    model: 'Provinces',
                    limit: 1000,
                    offset: 0,
                    orderBy: 'id asc'
                };
                //省
                api.getDataList(body).then(res => {
                    this.loading.isLoading = false;
                    let data = res.data.data.data;
                    // if(roleState === '3') {
                    for (const item of data) {
                        let one = {
                            value: item.province_name + ',' + item.id,
                            label: item.province_name,
                            id: item.id,
                            type: 0
                        };
                        this.province.push(one)
                    }
                    // }else {
                    for (const item of data) {
                        let area = {
                            value: item.province_name,
                            label: item.province_name,
                            id: item.id,
                            children: [],
                            loading: false,
                            type: 0
                        };
                        let town = {
                            value: item.province_name,
                            label: item.province_name,
                            id: item.id,
                            children: [],
                            loading: false,
                            type: 0
                        };
                        this.area.push(area);
                        this.town.push(town);
                    }
                    // }
                })
            },

            loadAreaData(item, callback) {
                this.loadData(1, item, callback);
            },

            loadTownData(item, callback) {
                this.loadData(2, item, callback);
            },

            loadData(status, item, callback) {
                item.loading = true;
                if (item.type === 0) {
                    let body = {
                        model: 'Citys',
                        limit: 1000,
                        offset: 0,
                        orderBy: 'id asc',
                        condition: {
                            province_id: item.id
                        }
                    };
                    //市
                    api.getDataList(body).then(res => {
                        let data = res.data.data.data;
                        let city = [];
                        if (status === 2) {
                            for (const citys of data) {
                                let one = {
                                    value: citys.city_name + ',' + citys.id,
                                    label: citys.city_name,
                                    id: citys.id,
                                    type: 1
                                };
                                city.push(one)
                            }
                        } else {
                            for (const citys of data) {
                                let one = {
                                    value: citys.city_name,
                                    label: citys.city_name,
                                    id: citys.id,
                                    children: [],
                                    loading: false,
                                    type: 1
                                };
                                city.push(one)
                            }
                        }
                        item.children = city;
                        item.loading = false;
                        callback();
                    })
                } else if (item.type === 1) {
                    let body = {
                        model: 'Areas',
                        limit: 1000,
                        offset: 0,
                        orderBy: 'id asc',
                        condition: {
                            city_id: item.id
                        }
                    };
                    //区
                    api.getDataList(body).then(res => {
                        let data = res.data.data.data;
                        let area = [];
                        for (const areas of data) {
                            let one = {
                                value: areas.area_name + ',' + areas.id,
                                label: areas.area_name,
                            };
                            area.push(one)
                        }
                        item.children = area;
                        item.loading = false;
                        callback();
                    })
                }

            },
            
        }
    }

</script>


<style lang="less">
    @import '../../assets/styles/constant.less';

    .old-user-list {
        width: 100%;
        height: 100%;
        overflow-x: hidden;
        overflow-y: auto;
        background-color: #f5f7f9;

        .ivu-layout {
            min-height: 100%;
        }

        .header {
            font-size: 14px;
            line-height: 40px;
            height: 40px !important;
            color: #434343;
            padding: 0 50px;
            background-color: @background;
            border-bottom: 1px solid #ddd;

            .border-left {
                border-left: 5px solid @baseColor;
                margin-right: 4px;
            }
        }

        .content {
            width: 100%;
            min-height: 76%;
            padding: 20px 60px;

            .search-box {
                .search-btn {
                    width: 100px;
                    height: 32px;
                    line-height: 32px;
                    text-align: center;
                    background-color: @greenColor;
                    border-radius: 4px;
                    color: #fff;
                    cursor: pointer;
                }
            }

            .table-box {
                margin-top: 20px;
                width: 100%;

                .el-table th {
                    background-color: #eee;
                    color: #333;
                    font-size: 14px;
                }

                .el-button--text {
                    color: @greenColor;
                }
            }

            .dialog_box {
                .role_edit_box {
                    display: flex;
                    .ivu-form-item-content {
                        display: flex;
                    }
                    .u_list {
                        display: flex;
                        // flex-wrap: wrap;
                        .one {
                            border: 1px dashed #aaa;
                            padding: 0 10px;
                            margin-right: 10px;
                            height: 32px;
                        }
                    }
                }
                .ivu-input[disabled] {
                    color: #666;
                }

                .fead {
                    transition: all 0.3s;
                }

                .fead.show {
                    height: auto;
                    margin-bottom: 24px;
                    overflow: initial;
                }

                .hidden {
                    height: 0;
                    overflow: hidden;
                    margin-bottom: 0;
                }
                .u_content {
                    margin-left: 120px;
                    display: flex;
                    flex-wrap: wrap;
                }
                .u_input {
                    width:200px;
                    display: inline-block;
                    margin-right: 4px;
                    margin-bottom: 10px;
                }
                .addBtn {
                    display: inline-block;
                    border: 1px dashed #aaa;
                    padding: 0 10px;
                    height: 32px;
                    cursor: pointer;
                }
            }

            .page-box {
                height: 50px;
                line-height: 50px;
                text-align: right;
                background-color: #fff;
                padding: 0 20px;
            }
        }

        .copy-right {
            text-align: center;
            color: #aaa;
            font-size: 12px;
        }
    }
    #old-user-list {
        .right .ivu-form-item-content {
            text-align: right;
        }
        .ivu-form-item-content .el-checkbox-group{
            display: flex;
            flex-wrap: wrap;
            // justify-content: space-between;
            .el-checkbox--mini {
                margin-top: 0;
                margin-left: 0;
                margin-right: 10px;
                margin-bottom: 10px;
                width: 22%;
                min-width: 96px;
            }
        }
        .fead {
            transition: all 0.3s;
        }

        .fead.show {
            height: auto;
            margin-bottom: 24px;
            overflow: initial;
        }

        .hidden {
            height: 0;
            overflow: hidden;
            margin-bottom: 0;
        }
        .u_content {
            margin-left: 120px;
            display: flex;
            flex-wrap: wrap;
        }
        .u_input_box {
            display: flex;
            flex-wrap: wrap;
            width: 100%;
        }
        .u_input {
            width:200px;
            display: inline-block;
            margin-right: 4px;
            margin-bottom: 10px;
        }
        .addBtn {
            display: inline-block;
            border: 1px dashed #aaa;
            padding: 0 10px;
            height: 32px;
            cursor: pointer;
            margin-left: 10px;
        }
    }
</style>
